import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, Tabs, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, RadarChartOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.css';

interface LoginForm {
    username: string;
    password: string;
    autoLogin?: boolean;
}

interface RegisterForm {
    username: string;
    password: string;
    email: string;
}

const Login: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const [loginForm] = Form.useForm();
    const [registerForm] = Form.useForm();

    const handleLogin = async (values: LoginForm) => {
        try {
            setLoading(true);
            const response = await fetch('/api/user/doLogin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: values.username,
                    password: values.password,
                    email: '',
                    userId: 0
                }),
            });

            const data = await response.json();

            if (response.ok && data.code === 200) {
                // 使用后端返回的用户信息
                const userInfo = {
                    username: data.data.username,
                    userId: data.data.userId,
                    email: data.data.email
                };
                if (values.autoLogin) {
                    localStorage.setItem('user', JSON.stringify(userInfo));
                }
                message.success('登录成功');
                navigate('/text/upload');
            } else {
                message.error(data.message || '登录失败，请检查用户名和密码');
            }
        } catch (error) {
            message.error('登录失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    const handleRegister = async (values: RegisterForm) => {
        try {
            setLoading(true);
            const response = await fetch('/api/user/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: values.username,
                    password: values.password,
                    email: values.email,
                    userId: 0
                }),
            });

            const data = await response.json();

            if (response.ok && data.code === 200) {
                message.success('注册成功，请登录');
                registerForm.resetFields();
                // 切换到登录标签页
                setActiveKey('account');
            } else {
                message.error(data.message || '注册失败，请稍后重试');
            }
        } catch (error) {
            message.error('注册失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    const [activeKey, setActiveKey] = useState('account');

    return (
        <div className={styles.container}>
            <div className={styles.backgroundDecoration}>
                <div className={styles.backgroundGrid}></div>
                <div className={styles.backgroundCircles}>
                    <div className={`${styles.backgroundCircle} ${styles.circle1}`}></div>
                    <div className={`${styles.backgroundCircle} ${styles.circle2}`}></div>
                </div>
            </div>
            <div className={styles.content}>
                <div className={styles.top}>
                    <div className={styles.header}>
                        <RadarChartOutlined className={styles.logo} />
                        <span className={styles.title}>文本相似度分析</span>
                    </div>
                    <div className={styles.desc}>西湖区最具影响力的文本分析工具</div>
                </div>

                <div className={styles.main}>
                    <Tabs
                        activeKey={activeKey}
                        onChange={setActiveKey}
                        centered
                        items={[
                            {
                                key: 'account',
                                label: '账户密码登录',
                                children: (
                                    <Form
                                        form={loginForm}
                                        name="login"
                                        onFinish={handleLogin}
                                        initialValues={{ autoLogin: true }}
                                    >
                                        <Form.Item
                                            name="username"
                                            rules={[{ required: true, message: '请输入用户名' }]}
                                        >
                                            <Input
                                                prefix={<UserOutlined />}
                                                placeholder="用户名"
                                                size="large"
                                            />
                                        </Form.Item>
                                        <Form.Item
                                            name="password"
                                            rules={[{ required: true, message: '请输入密码' }]}
                                        >
                                            <Input.Password
                                                prefix={<LockOutlined />}
                                                placeholder="密码"
                                                size="large"
                                            />
                                        </Form.Item>
                                        <Form.Item>
                                            <div className={styles.formOptions}>
                                                <Form.Item
                                                    name="autoLogin"
                                                    valuePropName="checked"
                                                    noStyle
                                                >
                                                    <Checkbox>自动登录</Checkbox>
                                                </Form.Item>
                                            </div>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button
                                                type="primary"
                                                htmlType="submit"
                                                loading={loading}
                                                block
                                                size="large"
                                            >
                                                登录
                                            </Button>
                                        </Form.Item>
                                    </Form>
                                ),
                            },
                            {
                                key: 'register',
                                label: '用户注册',
                                children: (
                                    <Form
                                        form={registerForm}
                                        name="register"
                                        onFinish={handleRegister}
                                    >
                                        <Form.Item
                                            name="username"
                                            rules={[{ required: true, message: '请输入用户名' }]}
                                        >
                                            <Input
                                                prefix={<UserOutlined />}
                                                placeholder="用户名"
                                                size="large"
                                            />
                                        </Form.Item>
                                        <Form.Item
                                            name="password"
                                            rules={[
                                                { required: true, message: '请输入密码' },
                                                { min: 6, message: '密码长度不能小于6位' }
                                            ]}
                                        >
                                            <Input.Password
                                                prefix={<LockOutlined />}
                                                placeholder="密码"
                                                size="large"
                                            />
                                        </Form.Item>
                                        <Form.Item
                                            name="email"
                                            rules={[
                                                { required: true, message: '请输入邮箱' },
                                                { type: 'email', message: '请输入有效的邮箱地址' }
                                            ]}
                                        >
                                            <Input
                                                prefix={<MailOutlined />}
                                                placeholder="邮箱"
                                                size="large"
                                            />
                                        </Form.Item>
                                        <Form.Item>
                                            <Button
                                                type="primary"
                                                htmlType="submit"
                                                loading={loading}
                                                block
                                                size="large"
                                            >
                                                注册
                                            </Button>
                                        </Form.Item>
                                    </Form>
                                ),
                            },
                        ]}
                    />
                </div>

                <div className={styles.footer}>
                    <Button type="link" onClick={() => navigate('/')}>
                        返回首页
                    </Button>
                </div>
            </div>
        </div>
    );
};

export default Login;
